import 'dart:io';

import 'package:flutter/material.dart';

import 'package:get/get.dart';
import 'package:mqtt_client/mqtt_client.dart';
import 'package:mqtt_client/mqtt_server_client.dart';
import 'package:simudata_display/app/routes/app_pages.dart';
import 'package:simudata_display/app/services/mqtt_client_service.dart';

import '../controllers/login_controller.dart';

class LoginView extends GetView<LoginController> {
  final TextEditingController _serverIPController =
      TextEditingController(text: "127.0.0.1");
  final TextEditingController _serverPortController =
      TextEditingController(text: "1883");
  final TextEditingController _mqttClientIDController = TextEditingController();

  late MqttServerClient client;

  LoginView({super.key});

  void _onLoginPressed() async {
    MqttClientService clientService = Get.find();
    if (clientService.isConnected()) {
      return;
    }
    await clientService.connectToServer("127.0.0.1", "display1");
    clientService.subscribe("simu_device", 0);
    Get.toNamed(Routes.CHART_VIEW);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            SizedBox(
              width: 400,
              child: Column(children: [
                TextField(
                  controller: _serverIPController,
                  decoration: const InputDecoration(
                      border: OutlineInputBorder(),
                      labelText: "MQTT服务IP",
                      hintText: '请输入MQTT服务器IP地址'),
                ),
                ElevatedButton(
                    onPressed: _onLoginPressed, child: const Text('登录')),
              ]),
            )
          ],
        ),
      ),
    );
  }
}
